package com.anywhere.freightman.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anywhere.freightman.common.entity.car.LocationEntity;
import com.anywhere.freightman.common.entity.car.TrackPoint;
import com.anywhere.freightman.common.ex.CustomException;
import com.google.common.base.Strings;
import com.openapi.sdk.service.DataExchangeService;
import com.openapi.sdk.service.TransCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CarLocationTestOpenClient {
    private final static String CAR_LOCATION_TOKEN = "car_location_token";
    @Autowired
    private RedisClient redisClient;

    @Value("${car.location.testopen.username}")
    private String username;
    @Value("${car.location.testopen.pwd}")
    private String pwd;
    @Value("${car.location.testopen.client-id}")
    private String clientId;
    @Value("${car.location.testopen.host-name}")
    private String hostName;

    public String getToken() throws Exception {

        String token = redisClient.getString(CAR_LOCATION_TOKEN);
        if (Strings.isNullOrEmpty(token)) {
            String p = String.format("user=%s&pwd=%s", username, pwd);
            p = TransCode.encode(p);
            String url = hostName + "login/" + p + "?client_id=" + clientId;
            DataExchangeService service = new DataExchangeService(5000, 5000);
            String json = service.accessHttps(url, "post");
            JSONObject jsonObject = JSON.parseObject(json);
            checkStatusCode(jsonObject);
            token = jsonObject.getString("result");
            redisClient.setValue(CAR_LOCATION_TOKEN, token);
        }
        return token;
    }

    public LocationEntity getLastLocation(String carNumber) throws Exception {
        String token = getToken();
        String p = String.format("token=%s&vclN=%s&timeNearby=24", token, carNumber);
        p = TransCode.encode(p);
        String url = hostName + "vLastLocationV3/" + p + "?client_id=" + clientId;
        DataExchangeService service = new DataExchangeService(5000, 5000);
        String json = service.accessHttps(url, "post");
        System.out.println(json);
        JSONObject jsonObject = JSON.parseObject(json);
        checkStatusCode(jsonObject);
        return JSON.parseObject(jsonObject.getString("result"), LocationEntity.class);
    }

    public List<TrackPoint> getTrack(String carNumber, long startTime, long endTime) throws Exception {
        String token = getToken();
        Date startDate = new Date(startTime);
        Date entDate = new Date(endTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-d HH:mm:ss");
        String p = String.format("token=%s&vclN=%s&qryBtm=%s&qryEtm=%s",
                token, carNumber, sdf.format(startDate), sdf.format(entDate));
        p = TransCode.encode(p);
        String url = hostName + "vHisTrack24/" + p + "?client_id=" + clientId;
        DataExchangeService service = new DataExchangeService(5000, 5000);
        String json = service.accessHttps(url, "post");
        JSONObject jsonObject = JSON.parseObject(json);
        checkStatusCode(jsonObject);

        JSONArray result = jsonObject.getJSONArray("result");
        List<TrackPoint> pointList = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            JSONObject item = result.getJSONObject(i);
            TrackPoint trackPoint = JSON.parseObject(item.toJSONString(), TrackPoint.class);
            pointList.add(trackPoint);
        }

        return pointList;
    }

    public List<LocationEntity> getLastLocation(List<String> carNumbers) throws Exception {
        String token = getToken();
        String vclNs = "";
        List<String> vclNList = new ArrayList<>();
        if (carNumbers.size() <= 0) {
            throw new CustomException("请输入车牌号");
        } else {
            for (String item : carNumbers) {
                vclNList.add(item + "_1");
                vclNList.add(item + "_2");
            }
            vclNs = StringUtils.join(vclNList.toArray(), ",");
        }
        String p = String.format("token=%s&vclNs=%s&timeNearby=72", token, vclNs);
        p = TransCode.encode(p);
        String url = hostName + "vLastLocationMultiV4/" + p + "?client_id=" + clientId;
        DataExchangeService service = new DataExchangeService(5000, 5000);
        String json = service.accessHttps(url, "post");
        JSONObject jsonObject = JSON.parseObject(json);
        checkStatusCode(jsonObject);
        return JSON.parseArray(jsonObject.getString("result"), LocationEntity.class);
    }

    private void checkStatusCode(JSONObject jsonObject) {
        Integer statusCode = jsonObject.getInteger("status");
        switch (statusCode) {
            case 1002:
                throw new CustomException("接口错误-参数不正确");
            case 1003:
                throw new CustomException("接口错误-车辆调用数量已达上限");
            case 1004:
                throw new CustomException("接口错误-接口调用次数已达上限");
            case 1005:
                throw new CustomException("接口错误-该API账号未授权指定所属行政区划数据范围");
            case 1006:
                throw new CustomException("接口错误-无结果");
            case 1010:
                throw new CustomException("接口错误-用户名或密码不正确");
            case 1011:
                throw new CustomException("接口错误-IP不在白名单列表");
            case 1012:
                throw new CustomException("接口错误-账号已经禁用");
            case 1013:
                throw new CustomException("接口错误-账号已过有效期");
            case 1014:
                throw new CustomException("接口错误-无接口权限");
            case 1015:
                throw new CustomException("接口错误-用户认证系统已升级，请使用令牌访问");
            case 1016:
                throw new CustomException("接口错误-令牌失效");
            case 1017:
                throw new CustomException("接口错误-账号欠费");
            case 1018:
                throw new CustomException("接口错误-授权的接口已禁用");
            case 1019:
                throw new CustomException("接口错误-授权的接口已过期");
            case 1020:
                throw new CustomException("接口错误-该车调用次数已达上限");
            case 1021:
                throw new CustomException("接口错误-client_id不正确");
            case 9001:
                throw new CustomException("接口错误-系统异常");
            default:
                break;
        }
    }
}
